#include "todomodel.h"

#include <QLineEdit>

ItemDelegate::ItemDelegate(QObject *parent) : QStyledItemDelegate(parent)
{

}

QWidget * ItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QLineEdit *edit = new QLineEdit(parent);

    return edit;
}

void ItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    QString value = index.model()->data(index, Qt::EditRole).toString();

    QLineEdit *edit = static_cast<QLineEdit *>(editor);

    edit->setText(value);
}

void ItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    QLineEdit *edit = static_cast<QLineEdit *>(editor);
    QString value = edit->text();

    if (!value.trimmed().isEmpty()) {
        model->setData(index, value.trimmed(), Qt::EditRole);
    }
}

void ItemDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    editor->setGeometry(option.rect);
}

TodoModel::TodoModel(QObject *parent) : QAbstractItemModel(parent)
{

}

void TodoModel::addRow(QString text)
{
    beginInsertRows(QModelIndex(), m_lstData.size(), m_lstData.size());
    m_lstData.append(text);
    endInsertRows();
}

void TodoModel::deleteRow(int index)
{
    beginRemoveRows(QModelIndex(), index, index);
    m_lstData.removeAt(index);
    endRemoveRows();
}

int TodoModel::rowCount(const QModelIndex &parent) const
{
    return m_lstData.count();
}

int TodoModel::columnCount(const QModelIndex &parent) const
{
    return 1;
}

QVariant TodoModel::data(const QModelIndex &index, int role) const
{
    if (role == Qt::DisplayRole) {
        return m_lstData.at(index.row());
    }

    return QVariant();
}

QModelIndex TodoModel::index(int row, int column, const QModelIndex &parent) const
{
    return createIndex(row, column);
}

QModelIndex TodoModel::parent(const QModelIndex &index) const
{
    return QModelIndex();
}

Qt::ItemFlags TodoModel::flags(const QModelIndex &index) const
{
    Qt::ItemFlags flags = QAbstractItemModel::flags(index);
    flags |= Qt::ItemIsEditable;

    return flags;
}

bool TodoModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (index.isValid() && role == Qt::EditRole) {
        m_lstData.replace(index.row(), value.toString());
        return true;
    }

    return false;
}
